import './index.css'
import { Button, Upload, Flex,Input  } from 'antd';
import React,{useEffect, useState} from 'react';
import {SearchOutlined,UploadOutlined  } from '@ant-design/icons';
let Uploadt = () => {
      const [currentId2, setCurrentId2] = useState(1)
  const options2 = [

        { label: "图片", id: 1 },
    { label: "视频", id: 2 },
    { label: "音频", id: 3},
    ]
      const changeId2 = (id) => {
    setCurrentId2(id)
    }
    const fileList = [];
 const [imageUrls, setImageUrls] = useState([]);  
  const [videoUrls, setVideoUrls] = useState([]);  
  const [audioUrls, setAudioUrls] = useState([]);  
  useEffect(() => {  
    const savedImageUrls = localStorage.getItem('imageUrls') ? JSON.parse(localStorage.getItem('imageUrls')) : [];  
    const savedVideoUrls = localStorage.getItem('videoUrls') ? JSON.parse(localStorage.getItem('videoUrls')) : [];  
    const savedAudioUrls = localStorage.getItem('audioUrls') ? JSON.parse(localStorage.getItem('audioUrls')) : [];  
  
    setImageUrls(savedImageUrls);  
    setVideoUrls(savedVideoUrls);  
    setAudioUrls(savedAudioUrls);  
  }, []);
 const handleFileChange = (event) => {  
    const files = event.target.files;  
    if (!files.length) {  
      return;  
    }  
  
    const promises = [];  
  
    for (let i = 0; i < files.length; i++) {  
      const file = files[i];  
      const reader = new FileReader();  
      const promise = new Promise((resolve, reject) => {  
        reader.onload = (e) => {  
          if (e.target.result) {  
            resolve({ type: file.type, url: e.target.result });  
          } else {  
            reject('Failed to read file');  
          }  
        };  
        reader.onerror = (error) => {  
          reject(error);  
        };  
  
        if (file.type.startsWith('image/')) {  
          reader.readAsDataURL(file);  
        } else {  
          const url = URL.createObjectURL(file);  
          resolve({ type: file.type, url });  
        }  
      });  
  
      promises.push(promise);  
    }  
  
    Promise.all(promises)  
      .then((mediaUrls) => {  
        const updatedImageUrls = imageUrls.concat(  
          mediaUrls.filter(m => m.type.startsWith('image/')).map(m => m.url)  
        );  
        const updatedVideoUrls = videoUrls.concat(  
          mediaUrls.filter(m => m.type.startsWith('video/')).map(m => m.url)  
        );  
        const updatedAudioUrls = audioUrls.concat(  
          mediaUrls.filter(m => m.type.startsWith('audio/')).map(m => m.url)  
        );  
  
        setImageUrls(updatedImageUrls);  
        setVideoUrls(updatedVideoUrls);  
        setAudioUrls(updatedAudioUrls);  
  
        // 更新本地存储  
        localStorage.setItem('imageUrls', JSON.stringify(updatedImageUrls));  
        localStorage.setItem('videoUrls', JSON.stringify(updatedVideoUrls));  
        localStorage.setItem('audioUrls', JSON.stringify(updatedAudioUrls));  
      })  
      .catch((error) => {  
        console.error('Error reading files:', error);  
      });  
  };  
const deleteMedia = (mediaType, index) => {  
    let updatedUrls;  
    switch (mediaType) {  
      case 'image':  
        updatedUrls = [...imageUrls];  
        updatedUrls.splice(index, 1);  
        setImageUrls(updatedUrls);  
        break;  
      case 'video':  
        updatedUrls = [...videoUrls];  
        updatedUrls.splice(index, 1);  
        setVideoUrls(updatedUrls);  
        break;  
      case 'audio':  
        updatedUrls = [...audioUrls];  
        updatedUrls.splice(index, 1);  
        setAudioUrls(updatedUrls);  
        break;  
    }  
  
    // 更新本地存储  
    localStorage.setItem(mediaType + 'Urls', JSON.stringify(updatedUrls));  
  };   
    return (
        <div>
        <Input prefix={<SearchOutlined />} style={{ width: '90%', height: '40px', margin: '20px' }} placeholder="搜索图片" />
       
        <label style={{
          display: 'inline-block', cursor: 'pointer', overflow: 'hidden', position: 'relative', width: '95%', height: '40px', marginLeft: '10px', background: '#7830e6', border: 'none', color: '#fff', textAlign: 'center', lineHeight: '40px'
        }}>
          上传文件
          <input style={{opacity:0,position:'absolute',top:0,left:0,width:'100%',height:'100%'}} type='file' onChange={handleFileChange} />
        </label>
                <Button ghost style={{ width: '95%', height: '40px', margin: '10px', color: '#fff' }}>打开摄像头录制自己</Button>
                 {options2.map((item) => {
                          return (
                              <div key={item.id} onClick={() => changeId2(item.id)} className={item.id == currentId2 ? "active" : ""}>
                                      <div className='tpspyp' style={{float:'left'}}>{item.label}</div>
                            </div>
          )
                 })}
        {/* 图片 */}
                <div style={{width:'100%',height:'415px',overflowX:'hidden',overflowY:'scroll'}}>
                  <div style={{ display: currentId2 == 1 ? "block" : "none" }}>
{imageUrls.map((url, index) => (  
        <div key={index} style={{ float: 'left', marginRight: '10px' }}>  
          <img src={url} alt={`Uploaded Image ${index + 1}`} style={{ maxWidth: '100px', height: '100px' }} />  
          <button onClick={() => deleteMedia('image', index)}>删除</button>  
        </div>  
      ))} 
           
          </div>
          {/* 视频 */}
                  <div style={{ display: currentId2 == 2 ? "block" : "none" }}>
                   {videoUrls.map((url, index) => (  
        <div key={index}>  
          <video controls style={{ maxWidth: '100%' }}>  
            <source src={url} type="video/mp4" />  
            Your browser does not support the video tag.  
          </video>  
          <button onClick={(event) => deleteMedia('video', index,event)}>删除</button>  
        </div>  
      ))}  
          </div>
          {/* 音频 */}
                  <div style={{ display: currentId2 == 3 ? "block" : "none" }}>
                {audioUrls.map((url, index) => (  
        <div key={index}>  
          <audio controls style={{ maxWidth: '100%' }}>  
            <source src={url} type="audio/mpeg" />  
            Your browser does not support the audio tag.  
          </audio>  
          <button onClick={(event) => deleteMedia('audio', index,event)}>删除</button>  
        </div>  
      ))} 
                  </div>
                </div>
        </div>
)
}

export default Uploadt